<?php if (!defined('BASEPATH')) {
	exit('No direct script access allowed');
}

class Mmeter_read_model extends CI_Model {
	public function __construct() {
		parent::__construct();
	}


    public function get_mother_meters(){
        $sql = "SELECT * FROM ubs_mother_meter";
        $query = $this->db->query($sql);
        return $query->result();
    }


    public function get_latest_read($id){
        $sql = "SELECT * FROM ubs_mmeter_latest_readings_v WHERE mmeter_id = '".$id."' ";
        $query = $this->db->query($sql);
        return $query->result();
    }


    public function save_reads($data){
        $this->db->query("call ubs_mother_meter_readings_ins(?,?,?,?,?,?,?,?,?,@err,@msg)",$data);
        $que = $this->db->query("SELECT @err as error , @msg as msg");
        echo json_encode($que->result());
    }

    public function update_reads($data){
        $this->db->query("call ubs_mother_meter_readings_upd(?,?,?,?,@err,@msg)",$data);
        $que = $this->db->query("SELECT @err as error , @msg as msg");
        echo json_encode($que->result());
    }

    public function search_mm_read($id,$date){
        $add ="";
        if(!($date == 'xx')){
            $add = "AND CONCAT(ummr.read_year,'-',ummr.read_month) = '".$date."' "; 
        } 
        
        $sql = "SELECT umm.mother_name , ummr.* FROM ubs_mother_meter_readings ummr 
                    INNER JOIN ubs_mother_meter umm ON umm.mmeter_id = ummr.mmeter_id 
                WHERE ummr.mmeter_id = ".$id."  ".$add." ";

        $query = $this->db->query($sql);
        if($query->num_rows() != 0){
            return $query->result();
        }
        else {
            $result = "No results found.";
            return $result;
        }
    }

    public function search_reads_mm($id){
        $sql = "SELECT * FROM ubs_mother_meter_readings where mmeter_read_id = ".$id." ";
        $query = $this->db->query($sql);
        return $query->result();
    }

}